from collections import deque
from packet import packet
from constants import MAGIC

class packetholder(object):
  max_packets = None;
  max_flits = None; # Per packet

  contents = None

  def __init__(self, new_max_p, new_max_f=MAGIC.MAX_PSIZE):
    self.contents = deque()

    self.max_packets = new_max_p
    self.max_flits = new_max_f

  # accept_packet, return number of flits accepted
  def accept(self, inc_pkt, max_trans_f):
    # First, see if we already have this packet partially in buffers
    for pkt in self.contents:
      if (inc_pkt.compare(pkt)):
        accept_f = max(0, min(max_trans_f, inc_pkt.last_f - pkt.last_f, self.max_flits - (pkt.last_f-pkt.first_f)))
        
        pkt.u_last_f = pkt.last_f + accept_f
        return accept_f

    # Could not find packet so try to get space for it
    if (len(self.contents) < self.max_packets):
      new_pkt = packet(0)
      new_pkt.copy_from(inc_pkt)

      new_pkt.u_first_f = 0
      accept_f = min(max_trans_f, inc_pkt.last_f, self.max_flits)
      new_pkt.u_last_f = accept_f

      self.contents.append(new_pkt)
      return accept_f
    
    return 0

  def commit(self):
    remove_list = []

    for pkt in self.contents:
      pkt.first_f = pkt.u_first_f
      pkt.last_f = pkt.u_last_f

      # Check if pkt is transmitted, slate for removal
      if ((pkt.first_f == pkt.last_f) and (pkt.last_f == pkt.size_f)):
        remove_list.append(pkt)

    for victim in remove_list:
      self.contents.remove(victim)
